/* eslint-disable */
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
require('@babel/polyfill')
const friendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const webpack = require('webpack')
const ip = require('ip')
const Dotenv = require('dotenv-webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const loaderUtils = require('loader-utils')
const webpackbar = require('webpackbar')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HappyPack = require('happypack')
const TerserPlugin = require('terser-webpack-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')

function getCSSModuleLocalIdent(context, localIdentName, localName, options) {
  // Use the filename or folder name, based on some uses the index.js / index.module.(css|scss|sass) project style
  const fileNameOrFolder = context.resourcePath.match(
    /index\.module\.(css|scss|sass|less)$/
  )
    ? '[folder]'
    : '[name]'
  // Create a hash based on a the file location and class name. Will be unique across a project, and close to globally unique.
  const hash = loaderUtils.getHashDigest(
    path.posix.relative(context.rootContext, context.resourcePath) + localName,
    'md5',
    'base64',
    5
  )
  // Use loaderUtils to find the file or folder name
  const className = loaderUtils.interpolateName(
    context,
    `${fileNameOrFolder}_${localName}__${hash}`,
    options
  )
  // remove the .module that appears in every classname when based on the file.
  return className.replace('.module_', '_')
}

const { NODE_ENV } = process.env

const port = 8005

const hosts = new Map()
hosts.set('development', 'http://192.168.69.130:8888/')
hosts.set('test', 'http://8.136.225.110:8888/')
hosts.set('production', 'http://47.97.217.13:8888/')

module.exports = {
  mode: 'production',
  stats: {
    children: true // false 不输出子模块的打包信息
  },
  entry: ['@babel/polyfill', path.resolve(__dirname, './src/main.tsx')],
  // entry: {
  //   main: path.resolve(__dirname, '../src/index.tsx')
  // },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'js/[name].[chunkhash:6].bundle.js',
    publicPath: '/',
    assetModuleFilename: 'images/[hash:6][ext][query]'
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpackbar(), // 打包时美化进度条
    new MiniCssExtractPlugin({
      filename: 'css/[name].[chunkhash:8].css', // 生成的文件名
      chunkFilename: 'css/[id].[hash].css',
      ignoreOrder: true
    }),
    // new BundleAnalyzerPlugin({
    //   analyzerMode: "disable", // 不启用展示打包报告的web服务器
    //   generateStatsFile: true // 生成报告文件
    // }),
    // new CompressionPlugin(),
    new HappyPack({
      //用id来标识 happypack处理那里类文件
      id: 'babelid',
      //配置 babel-loader
      loaders: [
        {
          loader: 'babel-loader'
        }
      ],
      verbose: true
    }),
    new Dotenv({
      ignorSub: true
    }),
    new friendlyErrorsWebpackPlugin(),
    // new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '设备平台-灯控系统',
      template: path.resolve(__dirname, './index.html'),
      filename: 'index.html',
      favicon: path.resolve(__dirname, './src/favicon.svg')
    }),
    new webpack.ProvidePlugin({
      process: 'process/browser',
      Buffer: ['buffer', 'Buffer']
    })
  ],
  module: {
    rules: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader?cacheDirectory=true']
      },
      {
        test: /.tsx?$/,
        exclude: /node_modules/,
        use: 'ts-loader'
      },
      {
        test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
        exclude: /node_modules/,
        type: 'asset/resource'
      },
      {
        test: /\.(woff(2)?|eot|ttf|otf|svg)$/,
        exclude: /node_modules/,
        type: 'asset/inline'
      },
      {
        test: /\.css$/,
        exclude: /\.module\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
      },
      {
        test: /\.module\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              modules: {
                // localIdentName: '[name]_[local]_[hash:base64:5]',
                getLocalIdent: getCSSModuleLocalIdent
              }
            }
          },
          'postcss-loader'
        ]
      },
      {
        test: /\.less$/,
        exclude: /\.module\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                javascriptEnabled: true
              }
            }
          }
        ]
      },
      {
        test: /\.module\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              modules: {
                getLocalIdent: getCSSModuleLocalIdent
              }
            }
          },
          'postcss-loader',
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                javascriptEnabled: true
              }
            }
          }
        ]
      },
      {
        test: /\.s[ac]ss$/i,
        use: ['style-loader', 'css-loader', 'sass-loader']
      }
    ]
  },
  performance: {
    maxEntrypointSize: 1000000
  },
  devServer: {
    publicPath: '/',
    writeToDisk: false, // 将打包目录写入到硬盘 false为内存
    historyApiFallback: true, // 404 重定向到index.html
    contentBase: path.resolve(__dirname, './dist'), // 指定静态资源的根目录
    open: true, // 打开浏览器
    compress: true, // 压缩
    hot: true, // 热更新
    port: port, // 端口号
    host: 'dev.uchat.com.cn',
    allowedHosts: [
      'localhost',
      ip.address(),
      '0.0.0.0',
      '127.0.0.1',
      'dev.uchat.com.cn'
    ],
    proxy: {
      '/api': hosts.get(NODE_ENV),
      '/baiduApi': {
        target: 'https://aip.baidubce.com', //访问地址
        changeOrigin: true,
        secure: false, //只有代理https 地址需要次选项
        pathRewrite: {
          '^/baiduApi': ''
        }
      }
      // '/api': 'http://192.168.83.108:8888'
    }
  },
  externals: {
    // react: "React",
    // "react-dom": "ReactDOM",
    // "react-router": "ReactRouter",
    // "react-router-dom": "ReactRouterDOM",
    // antd: "antd",
  },
  node: {},
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], // 这几个后缀名的文件后缀可以省略不写
    alias: {
      '@': path.join(__dirname, './src'), // 这样 @就表示根目录src这个路径
      process: 'process/browser'
    },
    fallback: {
      assert: require.resolve('assert/')
    }
  },
  optimization: {
    sideEffects: true, // 处理副作用 代码(检查package.json文件)
    usedExports: true, // 开启 tree-shaking
    concatenateModules: true,
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: true, // 多线程并行构建
        terserOptions: {
          // https://github.com/terser/terser#minify-options
          compress: {
            warnings: false, // 删除无用代码时是否给出警告
            drop_debugger: true // 删除所有的debugger
            // drop_console: true, // 删除所有的console.*
            // pure_funcs: ["console.log"], // 删除所有的console.log
          }
        }
      }),
      new CssMinimizerPlugin()
    ],
    moduleIds: 'deterministic',
    chunkIds: 'deterministic',
    splitChunks: {
      chunks: 'all',
      automaticNameDelimiter: '-',
      minSize: 0,
      minRemainingSize: 0,
      hidePathInfo: true,
      maxSize: 50000,
      minChunks: 2,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      enforceSizeThreshold: 50000,
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          reuseExistingChunk: true
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    },
    runtimeChunk: {
      name: entrypoint => `runtime-${entrypoint.name}`
    }
  }
}
